<template>
  <div class="login-container">
    <img class="logo" src="../../assets/Login_logo.png" alt="" />
    <el-form
      v-if="!limit"
      class="login-form"
      autoComplete="on"
      :model="loginCode"
      ref="loginForm2"
      label-position="left"
    >
      <p class="title">欢迎使用</p>
      <p class="subtitle">请输入激活码</p>
      <el-form-item
        prop="code"
        :rules="[
          {
            required: true,
            trigger: 'blur',
            message: '激活码不能为空',
          },
        ]"
      >
        <el-input
          class="input"
          name="code"
          type="textarea"
          :rows="4"
          maxlength="100"
          v-model="loginCode.code"
          autoComplete="on"
          placeholder="请输入激活码"
          resize="none"
        />
      </el-form-item>
      <el-button
        class="btn"
        type="primary"
        :loading="loading2"
        @click.native.prevent="handlerRegister"
      >
        激 活
      </el-button>
    </el-form>
    <el-form
      v-else
      class="login-form"
      autoComplete="on"
      :model="loginForm"
      :rules="loginRules"
      ref="loginForm"
      label-position="left"
    >
      <p class="title">欢迎登录</p>
      <p class="subtitle">请输入账号密码</p>
      <el-form-item prop="username">
        <el-input
          class="input"
          name="username"
          type="text"
          v-model="loginForm.username"
          autoComplete="on"
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="input"
          name="password"
          :type="pwdType"
          @keyup.enter.native="handleLogin"
          v-model="loginForm.password"
          autoComplete="on"
          placeholder="请输入密码"
        ></el-input>
        <span v-if="pwdType === 'password'" class="show-pwd" @click="showPwd"
          ><svg-icon icon-class="eye"
        /></span>
        <span v-else class="show-pwd" @click="showPwd">
          <i class="el-icon-view"></i>
        </span>
      </el-form-item>
      <el-button
        class="btn"
        type="primary"
        :loading="loading"
        @click.native.prevent="handleLogin"
      >
        登 录
      </el-button>
    </el-form>
    <p class="footer">
      版权归“杭州千基生物科技有限公司”所有
    </p>
  </div>
</template>

<script>
import XLSX from "xlsx";
import ls from "../../utils/crypto";
import { ReadFile, writeFile } from "../../utils/tool";
import { parseTime } from "../../utils";
export default {
  name: "login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value || !value.trim()) {
        callback(new Error("请输入账号"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码不能小于6位"));
      } else {
        callback();
      }
    };
    return {
      loginCode: {
        code: "",
      },
      loading2: false,
      loginForm: {
        username: "admin",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePass },
        ],
      },
      loading: false,
      pwdType: "password",
      register: null,
      limit: false,
      errorCount: 0
    };
  },
  mounted() {
    const iv = {
      account: "admin",
      password: "Mlyx123456",
      register: null,
      errorLockTime: ""
    };
    const s = ls.setItem(JSON.stringify(iv));
    console.log(s);

    const d = ReadFile();
    if (d["register"]) {
      this.register = d["register"];

      const n = new Date().getTime();
      const l = new Date(this.register.limit).getTime() + 24 * 60 *60 * 1000;
      if (l > n) {
        this.logs(`已激活，到期时间${parseTime(new Date(this.register.limit).getTime(), '{y}-{m}-{d}')}`);
        this.limit = true;
      } else {
        this.logs(`激活已过期`);
        this.limit = false;
        writeFile({ register: null });
      }
    } else {
      this.logs(`未激活`);
    }

    const username = localStorage.getItem("login_username");

    this.loginForm.username = username || "admin";
  },
  methods: {
    showPwd() {
      if (this.pwdType === "password") {
        this.pwdType = "text";
      } else {
        this.pwdType = "password";
      }
    },
    handlerRegister() {
      this.$refs.loginForm2.validate((valid) => {
        if (valid) {
          this.loading2 = true;

          const str = ls.getItem(this.loginCode.code);
          console.log(str);

          if (str) {
            const res = JSON.parse(str);
            console.log(res);
            const n = new Date().getTime();
            const l = new Date(res.limit).getTime() + 24 * 60 *60 * 1000;
            if (l > n) {
              writeFile({ register: res });
              this.logs(`激活成功`);
              this.$message({
                message: "激活成功",
                type: "success",
              });
              this.register = res;
              this.limit = true;
            } else {
              this.logs(`激活失败，请联系客服`);
              this.$message({
                message: "激活失败，请联系客服",
                type: "error",
              });
            }
          }
          this.loading2 = false;
        }
      });
    },
    handleLogin() {
      const d = ReadFile();
      const n = Date.now();
      const durtion = n - d["errorLockTime"];
      if (durtion < 600000) {
        this.$alert(`因账号密码连续输错3次！您的账号已被锁定，请【${ Math.ceil(10 - durtion / 60000) }分钟】后再进行尝试登录`, "提示", {
            confirmButtonText: "确定",
            callback: (action) => {},
          });
          return
      }
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          let permission = [];
          const version = this.$store.state.app.version;
          if (version === "resister" || version === "tester") {
            permission = ["图片处理"];
          } else if (version === "gather") {
            permission = ["图像采集"];
          } else {
            permission = ["图像采集", "图片处理"];
          }

          this.$store
            .dispatch("user/Login", this.loginForm)
            .then((item) => {
              if (item) {
                this.logs("登录成功");
                this.loading = false;
                this.$store.commit("user/SET_TOKEN", "123456");
                this.$store.commit("user/SET_USERINFO", {
                  name: this.loginForm.username,
                  permission: JSON.stringify(permission),
                });
                localStorage.setItem("login_username", this.loginForm.username);
                this.$message({
                  message: "登录成功",
                  type: "success",
                });
                this.$router.push({ path: "/" });
              } else {
                this.loading = false;
                this.$message.error("账号或密码错误!");
                this.errorCount++;
                if (this.errorCount >= 3) {
                  writeFile({
                    errorLockTime: Date.now()
                  })
                  this.logs(`登录失败${this.errorCount}次，账号或密码错误，账号锁定`);
                  this.errorCount = 0;
                } else {
                  this.logs(`登录失败${this.errorCount}次，账号或密码错误`);
                }
              }
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg: #2d3a4b;
$light_gray: #eee;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    width: 340px;
    height: 46px;
    border-radius: 2px 2px 2px 2px;
    background: #ffffff;
    /deep/ input {
      background: transparent;
      border: 1px solid #e5e6eb;
      // -webkit-appearance: none;
      border-radius: 0px;
      padding: 0 12px;
      height: 46px;
      font-size: 16px;
      color: #1d2129;
      line-height: 46px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background: url("../../assets/Login_bgc.png") 0 0 no-repeat;
  background-size: auto 100%;
  .logo {
    position: absolute;
    top: 40px;
    left: 40px;
    width: auto;
    height: 28px;
  }
  .footer {
    position: absolute;
    left: 50%;
    bottom: 10px;
    font-size: 12px;
    color: #4e5969;
    line-height: 24px;
    margin: 0;
    transform: translate(-50%, 0);
    white-space: nowrap;
  }
  .login-form {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 8.42%;
    width: 404px;
    height: 442px;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    padding: 64px 32px 0 32px;
    display: flex;
    flex-direction: column;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    &_login {
      font-size: 20px;
    }
  }
  .title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #165dff;
    line-height: 28px;
  }
  .subtitle {
    margin: 12px 0 48px 0;
    font-size: 16px;
    color: #4e5969;
    line-height: 19px;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .btn {
    margin-top: 10px;
    width: 340px;
    height: 50px;
    background: #165dff;
    border-radius: 25px 25px 25px 25px;
    font-size: 18px;
    font-weight: 500;
    color: #ffffff;
    line-height: 21px;
    text-shadow: 0px 1px 2px rgba(19, 66, 185, 0.37);
  }
}
</style>
